<template>
  <div class="_battles-item" :class="{ _mobile: isMobile }">
    <template v-if="!props.loading">
      <div class="_battles-item-container">
        <div class="_battles-left-container">
          <div class="_text">{{ props.battle?.mode }}</div>
          <ul class="_battle-user-list">
            <li
              class="flex items-center gap-0.3rem"
              v-for="(user, idx) in users"
              :key="user?.id || idx"
            >
              <template v-if="user === null">
                <loading class="!w-1.88rem" :track-width="3" />
              </template>
              <template v-else>
                <div
                  class="w-1.88rem h-1.88rem rounded-full"
                  style="border: 1px solid #333"
                >
                  <img
                    class="w-full h-full"
                    style="object-fit: contain"
                    :src="user?.head"
                  />
                </div>
              </template>
              <template v-if="idx !== users.length - 1">
                <img class="w-1.05rem" :src="battleIcon" />
              </template>
            </li>
          </ul>
          <div class="_cost">
            <span class="_text">cost:</span>
            <div class="text-hex-fff text-1.13rem leading-1.31rem">
              <span class="mr-0.2rem">$</span>
              <span>{{ props.battle?.cost_amount || "--" }}</span>
            </div>
          </div>
        </div>

        <!-- box-list -->
        <div class="_battle-box-list">
          <ul
            ref="boxListRef"
            class="flex items-stretch gap-0.81rem m-0 p-0 list-none h-full"
          >
            <li
              class="_battle-box"
              :class="{
                _active: BattleBoxStatus.Battleing === Number(box.is_battling),
              }"
              v-for="box in boxList"
              :key="box.id"
            >
              <img
                class="h-full"
                style="object-fit: contain"
                :src="box.image"
              />

              <!-- arrow -->
              <img
                v-if="BattleBoxStatus.Battleing === Number(box.is_battling)"
                class="_battle-active-arrow"
                :src="boxActiveArrow"
              />
            </li>
          </ul>

          <!-- Box -->
          <div class="_box-info">
            <img :src="Box" />
            <div>{{ boxList.length }}</div>
          </div>
        </div>
        <div class="_battles-right-container">
          <el-button
            class="_btn"
            v-if="
              props.battle?.status === BattleStatus.BattleWait &&
              props.battle.battle_user_list.length <
                Number(props.battle.total_user_count)
            "
            type="primary"
            @click="onJoinBattle"
          >
            Join Battle
          </el-button>
          <el-button
            class="_btn"
            v-if="
              props.battle?.status !== BattleStatus.BattleWait ||
              props.battle.battle_user_list.length ===
                Number(props.battle.total_user_count)
            "
            type="info"
            @click="onJoinBattle"
          >
            View Battle
          </el-button>
        </div>
      </div>
    </template>
    <template v-else>
      <div class="flex items-center justify-center h-full">
        <loading class="!w-2.5rem" :track-width="6" />
      </div>
    </template>
  </div>
</template>

<script lang="tsx" setup>
import { ElMessageBox } from "element-plus";

import { joinBattle } from "@/api/battles";
import { onBuriedPoint } from "@/api/user";
import battleIcon from "@/assets/battle.png";
import boxActiveArrow from "@/assets/box-active-arrow.png";
import Box from "@/assets/box-white.png";
import Loading from "@/components/Loading/loading.vue";
import { BattleBoxStatus, BattleStatus } from "@/enum/battle";
import { useMedia } from "@/hooks/useMedia";
import { useAuth } from "@/store/auth";

import { battleItemProps } from "./battleItem";

const props = defineProps(battleItemProps);

const router = useRouter();
const route = useRoute();
const auth = useAuth();
const isMobile = useMedia();

const boxListRef = ref<HTMLUListElement>();
const transformX = ref(0);

const users = computed(() => {
  const battle_user_list = props.battle?.battle_user_list || [];
  return new Array(Number(props.battle?.total_user_count || 0))
    .fill(null)
    .map((_user, idx) => {
      return battle_user_list[idx] || null;
    });
});

const boxList = computed(() => {
  return props.battle?.battle_box_list || [];
});

// 将正在battle中的盒子放置到可见范围内
watchEffect(async () => {
  if (!boxListRef.value) {
    return;
  }

  if (
    props.loading === false &&
    boxList.value.length !== 0 &&
    props.battle.status === BattleStatus.Battleing
  ) {
    await nextTick();
    if (!boxListRef.value) {
      return;
    }
    // 这里做了一次延时, 防止盒子列表的宽度还没计算出来
    await new Promise((resolve) => setTimeout(resolve, 500));
    const scrollWidth = boxListRef.value?.scrollWidth;
    const offsetWidth = boxListRef.value?.offsetWidth;
    if (scrollWidth <= offsetWidth) {
      return;
    }

    const activeLi = Array.from(boxListRef.value?.children || []).find(
      (children) => children.classList.contains("_active")
    ) as HTMLLIElement;
    if (!activeLi) {
      return;
    }

    const leftWidth = activeLi.offsetLeft + activeLi.offsetWidth;
    if (leftWidth > offsetWidth) {
      const diff = offsetWidth - leftWidth;
      if (transformX.value !== diff) {
        transformX.value = diff;
        boxListRef.value?.setAttribute(
          "style",
          `transform: translateX(${transformX.value}px);transition: all .3s`
        );
      }
    }
  }
});

function onJoinBattle() {
  const users = (props.battle.battle_user_list || []).map((item) => item.id);
  if (
    props.battle?.status !== BattleStatus.BattleWait ||
    users.includes(auth.userId + "") ||
    users.length === Number(props.battle.total_user_count)
  ) {
    router.push(`/battles/${props.battle?.battle_id}`);
  } else {
    ElMessageBox.confirm(
      `Confirm to cost $${props.battle?.cost_amount} to join battle?`,
      "",
      {
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
        cancelButtonClass: "el-button--info",
        type: "warning",
        callback: async (res) => {
          if (res === "confirm") {
            const result = await joinBattle({
              battle_id: props.battle?.battle_id,
            });
            if (result) {
              auth.getUserAssets();
              router.push(`/battles/${result?.battle_id}`);
            }
          }
        },
      }
    );
  }

  onBuriedPoint({
    page_name: `${route.meta.name}`,
    action: "按钮点击",
    button_name:
      props.battle?.status === BattleStatus.BattleWait
        ? "Join Battle"
        : "View Battle",
    battle_id: props.battle?.battle_id + "",
  });
}
</script>

<style lang="less" scoped>
._battles-item {
  width: 100%;
  aspect-ratio: 61.81 / 8.75;
  min-height: 0;
  border: solid 1px transparent;
  background-image: linear-gradient(
      var(--realbox-bg-box),
      var(--realbox-bg-box)
    ),
    linear-gradient(152deg, #73ebe777 0%, var(--realbox-bg-box) 20%);
  background-origin: border-box;
  background-clip: content-box, border-box;
  border-radius: var(--el-border-radius-base);
}

._battles-item-container {
  @apply flex items-stretch w-full h-full overflow-hidden text-hex-9D9D9D;
  ._battles-left-container {
    @apply w-0 flex flex-col items-center justify-center;
    flex: 2.65;
    ._text {
      font-size: 0.88rem;
      line-height: 1rem;
    }

    ._battle-user-list {
      @apply flex list-none m-0 p-0;
      gap: 0.5rem;
      margin: 0.88rem 0 0.75rem;
    }

    ._cost {
      @apply flex items-center;
      gap: 0.88rem;
    }
  }

  ._battle-box-list {
    @apply relative h-full w-0 overflow-hidden;
    flex: 5;
    padding: 0.94rem 0.81rem 0.88rem;
    &:after,
    &:before {
      @apply absolute top-0 bottom-0;
      width: 0.06rem;
      background-color: rgba(29, 31, 32, 1);
      content: "";
    }

    &:before {
      left: 0;
    }

    &:after {
      right: 0;
    }

    ._battle-box {
      position: relative;
      opacity: 0.3;
      height: 100%;
      min-width: 4.5rem;
      transition: all 0.3s;
      &._active {
        opacity: 1;
      }

      ._battle-active-arrow {
        position: absolute;
        z-index: 222;
        top: -0.94rem;
        left: 50%;
        transform: translateX(-50%);
        width: 0.88rem;
        object-fit: contain;
      }
    }

    ._box-info {
      @apply flex;
      gap: 0.88rem;
      padding: 0.25rem 0.81rem;
      position: absolute;
      top: 0.56rem;
      right: 0.38rem;
      color: #fff;
      background-color: #464a4b;
      border-radius: var(--el-border-radius-base);
      font-size: 0.88rem;
      line-height: 1rem;
      img {
        width: 0.81rem;
        height: 0.88rem;
      }
    }
  }

  ._battles-right-container {
    @apply w-0 flex flex-col items-center justify-center;
    flex: 2.1;
    ._btn {
      font-weight: 500;
      font-size: 0.88rem;
      line-height: 1.25rem;
      padding: 0.56rem 1.06rem !important;
    }
  }
}

._battles-item {
  &._mobile {
    aspect-ratio: 21.69 / 19.25;
    ._battles-item-container {
      @apply flex-col;
      padding: 0.56rem 0.63rem 0.81rem;
      ._battles-left-container,
      ._battle-box-list,
      ._battles-right-container {
        @apply w-full;
        flex: auto;
      }

      ._battles-left-container {
        ._battle-user-list {
          margin: 0.63rem 0 0.94rem;
        }

        ._cost {
          font-size: 1rem;
          line-height: 1.13rem;
        }
      }

      ._battle-box-list {
        margin: 0.63rem 0 0.75rem;
        padding: 1.5rem 0.19rem 0.19rem;
        background: #313334;
        border-radius: 0.28rem;
        border: 0.05rem solid #464a4b;
        ._battle-box {
          min-width: auto;
          ._battle-active-arrow {
            top: -0.56rem;
            transform: translate(-50%, -100%);
          }
        }

        ._box-info {
          top: 0.25rem;
          right: 0.25rem;
          gap: 0.44rem;
          background-color: #1d1f20;
          border-radius: 0.23rem;
          font-size: 0.88rem;
          img {
            width: 0.7rem;
          }
        }
      }

      ._battles-right-container {
        ._btn {
          height: 2.25rem;
        }
      }
    }
  }
}
</style>
